package com.leesche.zcsp.node.web.controller.web.v2.usermanage.admin;

import com.leesche.zcsp.node.utils.security.QEncodeUtil;
import com.leesche.zcsp.node.utils.web.gernerator.TimeGreaterUilt;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.model.*;
import com.leesche.zcsp.node.web.service.*;
import com.leesche.zcsp.node.web.service.impl.data.read.*;
import com.leesche.zcsp.node.web.service.impl.data.writ.AddTemplateRoleCommand;
import com.leesche.zcsp.node.web.service.impl.data.writ.AddUserInfoCommand;
import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import com.leesche.zcsp.node.web.vo.Principal;
import com.leesche.zcsp.node.web.vo.v2.FactoryUserVo;
import com.leesche.zcsp.node.web.vo.v2.Menu;
import com.leesche.zcsp.node.web.vo.v2.RoleVo;
import com.leesche.zcsp.node.web.vo.v2.UserBusinessInfo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Jerry Chan
 * @version V1.0
 *          ************ * Jerry Chan: * 2016/12/7 14:52: * 创建该类并实现业务逻辑: *********
 * @Title: WebIndividualController.java
 * @Description: TODO( “我的”Controller类)
 * @date 2016/12/7 14:52
 */
@Controller
@RequestMapping("/v2/admin/usermanage")
public class WebAdminUserManageController {

    private static final Logger logger = Logger.getLogger(WebAdminUserManageController.class);

    @Autowired
    private PrivilegeService privilegeService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleModuleService sysRoleModuleService;

    @Autowired
    private SysTemplateRoleModuleService sysTemplateRoleModuleService;

    @Autowired
    private SysTemplateRoleService sysTemplateRoleService;


    private static final String ADMIN_USERS_USERINFO = "web/v2/usermanage/admin/userinfo";

    /**
     * @Title: showRateManageView(Model model)
     * @Description: TODO(显示增加系统用户角色界面)
     * @author Jerry Chan
     * @date 2016/12/12 19:40
     */
    @RequestMapping(value = "/businssuser", method = RequestMethod.GET)
    public String showBusinssView(Model model) {
        return ADMIN_USERS_USERINFO;
    }

    /**
     * @Title: getRoles
     * @Description: TODO(新增用户)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "adduser", method = RequestMethod.POST)
    public Map<String, Object> addUserInfo(AddUserInfoCommand childUser) {
        try {
            String username = childUser.getUsername();
            if (username == null || "".equals(username)) {
                return WebResult.failure("用户名不能为空").toMap();
            } else {
                QuerySysUserCondition condition = new QuerySysUserCondition();
                condition.setUsername(childUser.getUsername());
                List<SysUserDto> sysUserDtos = sysUserService.findListsByCondition(condition);
                if (sysUserDtos != null || sysUserDtos.size() > 0) {
                    return WebResult.failure("'" + username + "'用户名已经存在，请使用其他用户名").toMap();
                }
            }

            String mobile = childUser.getMobile();
            if (mobile == null || "".equals(mobile)) {
                return WebResult.failure("手机号码不能为空").toMap();
            } else {
                QuerySysUserCondition condition = new QuerySysUserCondition();
                condition.setMobile(childUser.getMobile());
                List<SysUserDto> sysUserDtos = sysUserService.findListsByCondition(condition);
                if (sysUserDtos != null || sysUserDtos.size() > 0) {
                    return WebResult.failure("'" + mobile + "'用户名已经存在，请使用其他用户名").toMap();
                }
            }

            Long userid = privilegeService.getCurrentPrincipal().getUserid();
            SysUser newUser = new SysUser();
            newUser.setNtype(childUser.getNtype());//3表示工厂系统用户,4表示娱乐城老板
            newUser.setPuserid(userid);
            newUser.setAdminid(userid);
            newUser.setOuttime(TimeGreaterUilt.specifiedTime(Calendar.YEAR, childUser.getTimeDifference() <= 0 ? 3
                    : childUser.getTimeDifference()));
            newUser.setMobile(childUser.getMobile());
            newUser.setPassword(QEncodeUtil.md5Encrypt(childUser.getPassword()));
            newUser.setRemark(childUser.getRemark());
            newUser.setProperty(childUser.getProperty());
            newUser.setState(childUser.getState());
            newUser.setCreatetime(new Date());
            if (sysUserService.insertSelective(newUser) > 0) {
                return WebResult.success().toMap();
            } else {
                return WebResult.failure("新增用户失败，请稍后重试").toMap();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }

    }

    /**
     * @return
     * @Title: removeUserInfo(Long userid)
     * @Description: TODO(停用/启用用户)
     * @author Jerry Chan
     * @date 2017/1/21 15:09
     */
    @ResponseBody
    @RequestMapping(value = "disableuser")
    public Map<String, Object> disablieUser(Long userid) {
        try {

            QuerySysUserCondition condition = new QuerySysUserCondition();
            condition.setUserid(userid);
            SysUserDto userDto = sysUserService.findByCondition(condition);
            if (userDto != null) {
                return WebResult.failure("用户不存在，请重试").toMap();
            } else {
                SysUser user = new SysUser();
                user.setUserid(userid);
                switch (userDto.getState()) {
                    case 1:
                        user.setState(2);
                        break;
                    case 2:
                        user.setState(1);
                        break;
                    default:
                        return WebResult.failure("无法启用/停用该用户").toMap();
                }
                user.setAdminid(privilegeService.getCurrentPrincipal().getUserid());
                user.setUpdatetime(new Date());
                if (sysUserService.updateByPrimaryKeySelective(user) > 0)
                    return WebResult.success().toMap();
                else
                    return WebResult.failure("启用/停用该用户失败，请联系管理员").toMap();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: recoverPassowrd(final Long userid)
     * @Description: TODO(重置子账户密码)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "recoverpassword", method = RequestMethod.POST)
    public Map<String, Object> recoverPassowrd(final Long userid) {
        try {
            SysUser newUser = new SysUser();
            newUser.setUserid(userid);
            newUser.setAdminid(privilegeService.getCurrentPrincipal().getUserid());
            newUser.setUpdatetime(new Date());
            newUser.setPassword(QEncodeUtil.md5Encrypt(Constants.NOTIC_DEFAULT_USER_PASSWORD));
            if (sysUserService.updateByPrimaryKeySelective(newUser) > 0)
                return WebResult.success().toMap();
            else
                return WebResult.failure("恢复密码失败，请稍后重试").toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: getUserPlaces
     * @Description: TODO(设置角色权限)
     * @author Jerry Chan
     * @date 2016/12/20 17:50
     */
    @ResponseBody
    @RequestMapping(value = "authorization", method = RequestMethod.POST)
    public Map<String, Object> setRoleModule(Long roleid, Long[] modules) {
        try {
            if (roleid == null || roleid.equals(0)) {
                return WebResult.failure("角色为空,非法操作").toMap();
            } else if (modules == null || modules.length <= 0) {
                return WebResult.failure("权限为空,非法操作").toMap();
            } else {
                /* 设置角色的权限之前，先清空掉原来已经设置好的权限 */
                Long adminid = privilegeService.getCurrentPrincipal().getUserid();
                SysRoleModuleCriteria criteria = new SysRoleModuleCriteria();
                criteria.or().andRoleidEqualTo(roleid).andAdminidEqualTo(adminid);
                sysRoleModuleService.deleteByCriteria(criteria);

                List<SysRoleModule> sysRoleModules = new ArrayList<SysRoleModule>();
                Date updatetime = new Date();
                for (Long module : modules) {
                    SysRoleModule rm = new SysRoleModule();
                    rm.setRoleid(roleid);
                    rm.setModuleid(module);
                    rm.setAdminid(adminid);
                    rm.setUpdatetime(updatetime);
                    sysRoleModules.add(rm);
                }

                if (sysRoleModuleService.setupRoleModule(sysRoleModules) > 0) {
                    return WebResult.success().toMap();
                } else {
                    return WebResult.failure("角色授权失败,请与管理员联系").toMap();
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: templateAuthorization(Long templateid, Long[] templateModules)
     * @Description: TODO( 角色模版授权 )
     * @author Jerry Chan
     * @date 2017/2/4 14:53
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "templateauthorization", method = RequestMethod.POST)
    public Map<String, Object> templateAuthorization(Long templateid, Long[] templateModules) {

        try {
            if (templateid == null || templateid.equals(0)) {
                return WebResult.failure("模版角色为空,非法操作").toMap();
            } else if (templateModules == null || templateModules.length <= 0) {
                return WebResult.failure("权限为空,非法操作").toMap();
            } else {
                /* 设置模版角色的权限之前，先清空掉原来已经设置好的权限 */
                SysTemplateRoleModuleCriteria criteria = new SysTemplateRoleModuleCriteria();
                criteria.or().andTridEqualTo(templateid);
                sysTemplateRoleModuleService.deleteByCriteria(criteria);

                List<SysTemplateRoleModule> sysTemplateRoleModules = new ArrayList<SysTemplateRoleModule>();
                Long adminid = privilegeService.getCurrentPrincipal().getUserid();
                Date updateTime = new Date();
                for (Long templateModule : templateModules) {
                    SysTemplateRoleModule templateRoleModule = new SysTemplateRoleModule();
                    templateRoleModule.setModuleid(templateModule);
                    templateRoleModule.setTrid(templateid);
                    templateRoleModule.setAdminid(adminid);
                    templateRoleModule.setUpdatetime(updateTime);
                    sysTemplateRoleModules.add(templateRoleModule);
                }

                if (sysTemplateRoleModuleService.setupTemplateRoleModule(sysTemplateRoleModules) > 0) {
                    return WebResult.success().toMap();
                } else {
                    return WebResult.failure("授权失败,请稍后重试").toMap();
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /** 
     * @Title: addTemplateRole(AddTemplateRoleCommand templaterole)
     * @Description: TODO( 添加模版角色[可授权或不授权] )
     * @author Jerry Chan
     * @date 2017/2/4 14:54
     * @return 
     */
    @ResponseBody
    @RequestMapping(value = "addtemplaterole")
    public Map<String, Object> addTemplateRole(AddTemplateRoleCommand templaterole) {
        try {

            if (templaterole.getRolename() == null || "".equals(templaterole.getRolename())) {
                return WebResult.failure("模版名称不能为空").toMap();
            }

            SysTemplateRole sysTemplateRole = new SysTemplateRole();
            sysTemplateRole.setTrnamecn(templaterole.getRolename());
            sysTemplateRole.setIsdefault(templaterole.getIsdefault());
            sysTemplateRole.setIsshare(templaterole.getIsshare());
            sysTemplateRole.setUpdatetime(new Date());
            sysTemplateRole.setRemark(templaterole.getRemark());
            sysTemplateRole.setState(templaterole.getState());
            sysTemplateRole.setAdminid(privilegeService.getCurrentPrincipal().getUserid());
            sysTemplateRole.setTrnameen("user customer");
            sysTemplateRole.setUsertype(templaterole.getRoletype());

            if (sysTemplateRoleService.insertSelective(sysTemplateRole) > 0) {

                Long[] modules = templaterole.getModuleid();
                if (modules != null && modules.length > 0) {

                    List<SysTemplateRoleModule> strms = new ArrayList<SysTemplateRoleModule>();

                    Long adminid = privilegeService.getCurrentPrincipal().getUserid();
                    Date updatetime = new Date();
                    Long tid = sysTemplateRole.getTrid();
                    for (Long module : modules) {
                        SysTemplateRoleModule strm = new SysTemplateRoleModule();
                        strm.setUpdatetime(updatetime);
                        strm.setAdminid(adminid);
                        strm.setTrid(tid);
                        strm.setModuleid(module);
                        strms.add(strm);
                    }

                    sysTemplateRoleModuleService.setupTemplateRoleModule(strms);

                }
                return WebResult.success().toMap();

            } else {
                return WebResult.failure("新增角色模版失败，请稍后重试").toMap();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }


}
